import React from 'react'
import './index.css'

// 滚动容器组件
function Scroller(props) {
  // 停止滚动时显示滚动条的功能
  const [scrollTop, setScrollTop] = React.useState(0)
  // 滚动结束标识
  const [scrollEnd, setScrollEnd] = React.useState(true)
  const scrollRef = React.useRef()

  // 滚动处理
  let timeout = null
  const onScrollCaptureHandle = (e) => {
    if (scrollEnd !== false) {
      setScrollEnd(false)
    }
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      if (scrollEnd !== true) {
        setScrollTop(scrollRef.current.scrollTop)
      }
      // 一定要停止
      setScrollEnd(true)
    }, 250)
  }

  // onScrollHandle()
  const onScrollHandle = (e) => {
    console.log('onScrollHandle', e)
  }

  // 滚动到底部
  const scrollToBottom = () => {
    const current = scrollRef.current
    if (current) {
      current.scrollTop = current.scrollHeight
    }
    setScrollEnd(true)
  }

  // 滚动到顶部
  const scrollToTop = () => {
    const current = scrollRef.current
    if (current) {
      current.scrollTop = 0
    }
    setScrollEnd(true)
  }

  return (
    <div
      className={`scroller ${scrollEnd ? '' : 'scrolling'}`}
      ref={scrollRef}
      onScroll={(e) => onScrollHandle(e)}
      onScrollCapture={(e) => onScrollCaptureHandle(e)}
    >
      <div className='scroller_content'>
        {React.Children.map(props.children, (child, i) => {
          // 增加一些滚动控制方法属性给子组件
          return React.cloneElement(child, {
            scrollToBottom,
            scrollToTop,
            scrollTop,
            setScrollTop,
            setScrollEnd,
            scrollRef,
          })
        })}
      </div>
    </div>
  )
}

export default Scroller
